<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="mini" :model="pageData" layout="inline">
            <CorporateSectorCascader
              :configCascader="configCascader"
              @changeCascader="changeCascader"
            />
            <a-form-item label="仓库">
              <a-select
                popup-container="html"
                class="bacClass"
                :style="{ width: '10rem' }"
                v-model="pageData.b"
                allow-clear
              >
                <a-option v-for="item in fhWhList" :value="item.id">
                  {{ item.warehouseName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="原料编号">
              <a-input
                allow-clear
                :style="{ width: '10rem' }"
                class="bacClass"
                v-model="pageData.yarnCode"
              />
            </a-form-item>
            <a-form-item label="原料名称">
              <a-input
                allow-clear
                :style="{ width: '10rem' }"
                class="bacClass"
                v-model="pageData.yarnName"
              />
            </a-form-item>
            <a-form-item label="纱牌">
              <a-input
                allow-clear
                :style="{ width: '10rem' }"
                class="bacClass"
                v-model="pageData.yarnBrand"
              />
            </a-form-item>
            <a-form-item label="纱批">
              <a-input
                allow-clear
                :style="{ width: '10rem' }"
                class="bacClass"
                v-model="pageData.productionBatch"
              />
            </a-form-item>
            <a-form-item label="等级" label-col-flex="58px">
              <a-input
                allow-clear
                :style="{ width: '223px' }"
                class="bacClass"
                v-model="pageData.level"
              />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div style="text-align: right">
        <Toolbar
          :items="[`${permissionStore.hasPermisson('ysckc.cx') ? '查询' : ''}`, '导出']"
          @select="selectHandler"
          @export="exportExcel"
        >
        </Toolbar>
      </div>
      <div class="gang"></div>
    </template>
    <template #pageTabel>
      <a-tabs :lazy-load="true" :justify="true">
        <a-tab-pane title="原纱仓库存查询" :key="1">
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            :suppressDragLeaveHidesColumns="true"
            rowSelection="multiple"
            @grid-ready="gridReady"
            @columnResized="onColumnResized"
            @columnMoved="onColumnMoved"
            @columnVisible="onColumnVisible"
            style="height: calc(100% - 45px)"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="tableDataList"
            :columnDefs="tc"
            :localeText="localeText1"
            @FilterChanged="FilterChangeds"
          ></AgGridVuesCopys>
          <paginationCopys
            :page-size-options="pagingList1"
            :total="fySelet2.total"
            show-total
            show-jumper
            show-page-size
            @change="PageSize2"
            @page-size-change="change2"
            style="justify-content: center"
            :page-size="fySelet2.size"
            :current="fySelet2.page"
          />
        </a-tab-pane>
      </a-tabs>
    </template>
  </pageTabelLayout>
</template>
<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import { post, get } from '@/api/http'
  import { localeText } from '@/api/aggridZw'
  
  import Toolbar from '@/components/Toolbar.vue'
  import { exportJsonToExcel } from '@/api/Export2Excel'
  import { exportStyleExcel } from '@/api/Export2StyleExcel'
  import { Message, Modal } from '@arco-design/web-vue'
  import WHService from '@/service/wh'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import usePermission from '@/store/modules/permission'
  import emitter from '@/hooks/useEventBus'
  import { pagingList } from '@/api/paging'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import setTableTotalRow from '@/utils/setTableTotalRow.ts'
  import dayjs from 'dayjs'
  const pagingList1: any = ref(pagingList)
  const permissionStore = usePermission()
  const headerShow = ref(true)
  const localeText1: any = ref(localeText)

  const pageData: any = reactive({
    a: '',
    b: '',
    yarnCode: '',
    yarnName: '',
    yarnBrand: '',
    productionBatch: '',
    level: '',
  })

  const selectHandler = () => {
    fySelet2.page = 1
    wjYcList()
  }
  const tableDataList: any = ref([])
  const gridOption = ref()
  const colState = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
  }

  const fySelet2: any = reactive({
    total: 10,
    size: 10,
    page: 1,
  })

  const PageSize2 = (val: any) => {
    fySelet2.page = val
    wjYcList()
  }

  const change2 = (val: any) => {
    fySelet2.size = val
    wjYcList()
  }

  const tc = [
    {
      showRowGroup: 'hide_def',
      headerName: '',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
    {
      headerName: '公司',
      field: 'firm',
      // pinned: o['fixed'],
      width: 150,
    },
    {
      headerName: '仓库名称',
      field: 'warehouse',
      width: 150,
    },
    {
      headerName: '客户名称',
      field: 'customName',
      width: 150,
    },
    {
      headerName: '供应商名称',
      field: 'supplier',
      width: 150,
    },
    {
      headerName: '原料编号',
      field: 'yarnCode',
      width: 150,
    },
    {
      headerName: '原料名称',
      field: 'yarnName',
      width: 150,
    },
    {
      headerName: '纱牌',
      field: 'yarnBrand',
      width: 150,
    },
    {
      headerName: '纱批',
      field: 'productionBatch',
      width: 150,
    },
    {
      headerName: '等级',
      field: 'level',
      width: 150,
    },
    // {
    //     headerName: '可配色称',
    //     field: 'matchColor',
    //     width: 150
    // },
    {
      headerName: '色号',
      field: 'colorCode',
      width: 150,
    },
    {
      headerName: '色称',
      field: 'colorName',
      width: 150,
    },
    {
      headerName: '整件/个数',
      field: 'pieceCount',
      width: 150,
    },
    {
      headerName: '整件/件数',
      field: 'pieceNumber',
      width: 150,
    },
    {
      headerName: '整件/件重',
      field: 'pieceWeight',
      width: 150,
    },
    {
      headerName: '散件/个数',
      field: 'bulkCount',
      width: 150,
    },
    {
      headerName: '散件/件数',
      field: 'bulkNumber',
      width: 150,
    },
    {
      headerName: '散件/散重',
      field: 'bulkWeight',
      width: 150,
    },
    {
      headerName: '总数量',
      field: 'weightTotal',
      width: 150,
    },
    {
      headerName: '单位',
      field: 'unit',
      width: 150,
    },
    {
      headerName: '最近入库时间',
      field: 'stockInTime',
      width: 150,
    },
    {
      headerName: '存放天数',
      field: 'storagesDays',
      width: 150,
      valueFormatter: (params: any) => {
        const today = dayjs()
        const stockInTime = dayjs(params.data.stockInTime)
        const computedDays = today.diff(stockInTime, 'day')
        if (params.node.rowPinned !== 'bottom') return computedDays + 1
      },
    },
    {
      headerName: '库位',
      field: 'location',
      width: 150,
    },
    {
      headerName: '备注',
      field: 'remark',
      width: 150,
    },
  ]

  const wjYcList = () => {
    post({
      url: 'wms/yarnStock/getPage',
      data: {
        page: fySelet2.page,
        size: fySelet2.size,
        firm_id: pageData.a,
        warehouse_id: pageData.b,
        yarn_code: pageData.yarnCode,
        yarn_name: pageData.yarnName,
        yarn_brand: pageData.yarnBrand,
        production_batch: pageData.productionBatch,
        level: pageData.level,
      },
    }).then((res: any) => {
      gridOption.value.setRowData(res.data.list)
      setTableTotalRow(gridOption, res.data.list, [
        'pieceNumber',
        'bulkCount',
        'bulkNumber',
        'bulkWeight',
        'weightTotal',
      ])
      tableDataList.value = res.data.list
      fySelet2.total = res.data.total
    })
  }
  onMounted(() => {
    updateGridState01()
    wjYcList()
  })
  const configCascader = ref<{}>({
    corporateWidth: '200px', //公司宽度
    sectorWidth: '180px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'mini', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '选择公司', //公司label
    sectorName: '选择部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
  })
  const whService = new WHService()
  const fhWhList: any = whService.whList
  const changeCascader = (data: any) => {
    const { corporateId, sectorId, sectorLabel, corporateLabel } = data
    pageData.b = ''
    pageData.a = corporateId
    whService.getWarhouseListByFirmId(corporateId, '原纱仓')
  }

  /**
   * 导出EXCEL
   */
  const exportExcel = () => {
    let header = tc
      .map((o) => {
        return o.headerName
      })
      .splice(1)
    let filterCols = tc
      .map((c) => {
        return c.field
      })
      .splice(1)
    let data = formatJson(filterCols, tableDataList.value)
    exportStyleExcel({ header, data, filename: '原纱仓库存表.xlsx' })
  }

  /**
   * 过滤需要导出的列，并转换数据格式，如STATUS
   */
  const formatJson = (filterVal, jsonData) => {
    return jsonData.map((v) =>
      filterVal.map((j) => {
        if (!v[j]) {
          console.log(v[j])
          return ''
        }
        if (j == 'status') {
          if (v[j] == 1) {
            return '正常'
          } else {
            return '禁用'
          }
        } else {
          if (j) {
            return v[j]
          }
        }
      })
    )
  }
  const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
    saveOrUpdateGridState01('NventoryManagement4-1', gridOption, colState, tc)
  const onColumnMoved = () => {
    saveGridState01()
  }
  const onColumnResized = () => {
    saveGridState01()
  }
  const onColumnVisible = () => {
    saveGridState01()
  }
  const FilterChangeds = (params:any)=>{
    let data: any = {
      data: [],
    }
    params.api.forEachNodeAfterFilter((row: any) => {
      data.data.push(row.data)
    })
    setTableTotalRow(gridOption, data.data, [
        'pieceNumber',
        'bulkCount',
        'bulkNumber',
        'bulkWeight',
        'weightTotal'
      ])
  }
</script>
